package com.example.demo.listener;

import com.dangdang.ddframe.job.executor.ShardingContexts;
import com.dangdang.ddframe.job.lite.api.listener.AbstractDistributeOnceElasticJobListener;
import com.example.demo.mapper.TaskRepository;
import com.example.demo.pojo.JobTask;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * @ClassName ElasticJobListener
 * @Description TODO
 * @Author zhangshuai
 * @Date 2019/7/6 17:22
 * @Version 1.0
 **/
public class ElasticJobListener extends AbstractDistributeOnceElasticJobListener {

    @Resource
    private TaskRepository taskRepository;


    public ElasticJobListener(long startedTimeoutMilliseconds, long completedTimeoutMilliseconds) {
        super(startedTimeoutMilliseconds, completedTimeoutMilliseconds);
    }

    @Override
    public void doBeforeJobExecutedAtLastStarted(ShardingContexts shardingContexts) {

    }

    @Override
    public void doAfterJobExecutedAtLastCompleted(ShardingContexts shardingContexts) {

        //任务执行完成后更新用户性别为成功
        Optional<JobTask> byId = null;
        try {
            byId = taskRepository.findById(Long.valueOf(shardingContexts.getJobParameter()));
            if (byId.isPresent()) {
                JobTask jobTask = byId.get();
                jobTask.setStatus(1);
                try {
                    taskRepository.save(jobTask);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    System.out.println("jobTask:" + jobTask);
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
}
